#ifndef BOXLIST_H
#define BOXLIST_H

#include "ui_BoxList.h"
#include "XXUI_fix.h"
#include "qtreewidget.h"


class TreeItem : public QTreeWidgetItem
{
    Widget* widget;

public:
    TreeItem()
        : widget(nullptr)
        , parent(nullptr)
    {}

    ~TreeItem()
    {

    }

    static TreeItem* create() {
        TreeItem* item = new TreeItem;
        item->setCheckState(0, Qt::Checked);
        item->setFlags(item->flags() | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled);

        return item;
    }

    void setChecked(bool checked)
    {
        QTreeWidgetItem::setCheckState(0, checked ? Qt::Checked : Qt::Unchecked);
    }

    void setText(const char* text) {
        QTreeWidgetItem::setText(0, text);
    }

    void addChild(TreeItem* child) {
        child->parent = this;
        QTreeWidgetItem::addChild(child);
    }

    Widget* getWidget() { return widget; }
    void setWidget(Widget* w) { widget = w; }

    int childrenCount() {
        return childCount();
    }

    TreeItem* childrenAtIndex(int i)
    {
        return static_cast<TreeItem*>(child(i));
    }

    void removeAllChildren()
    {
        while (childCount() != 0)
        {
            removeChild(child(0));
        }
    }

    TreeItem* parent;
};

class Tree;

class BoxList : public QWidget
{
	Q_OBJECT

public:
	BoxList(QWidget *parent = 0);
	~BoxList();

    TreeItem* add(const QString& type, const QString& name, QTreeWidgetItem* parent = nullptr);
    TreeItem* root() { return _root; }
    TreeItem* current() { return _currentWidget; }

    TreeItem* findItem(Widget* w);
    QList<TreeItem*> getTopLevelItems();

    void onOpen(const QList<TreeItem*>&);

private slots:
	void showMenu(const QPoint& pos);

	void selectedNode(QTreeWidgetItem* curr, QTreeWidgetItem* prev);
    void onAdd(const QString& type);
    void onTouchMenu(int k);

    void checkNameAndVisible(QTreeWidgetItem*, int);
    void itemSelectionChanged();
    void onClick(QTreeWidgetItem*, int);

    virtual void keyPressEvent(QKeyEvent *event);
    virtual void keyReleaseEvent(QKeyEvent *event);
public slots:
    void onSelectionChanged();

signals :
    void onItemTextChanged(TreeItem* item);

    void onAddItem(TreeItem* newitem, const QString&, const QString&);
    void onDeleteItem(TreeItem* item);

private:

    void onDelete();
    void onCopy();
    void onSave();
    void onCode();
    void onCodeCpp();
    void onPaste();
    void onAddFrom();

	Ui::Form ui;
    Tree* _treeWidget;
	TreeItem* _currentWidget;
    TreeItem* _root;
    TreeItem* _copyed;

    bool _ctrlPress;

	int _index;
};

#endif // BOXLIST_H
